import utils from '../core/utils';
import logger from '../core/logger';
import apiInfo from './core/apiInfo';
import { clientBase } from './core/clientBase';
import { emoteResult } from '../enums/emoteResult';
import returnModel from '../model/common/returnModel';
import emotePackage from '../model/other/emotePackage';

class emoteClient extends clientBase {
  private result: emoteResult = emoteResult.failed;
  private _replyEmote: Array<emotePackage>;
  private _dynamicEmote: Array<emotePackage>;

  constructor() {
    super();
    this._replyEmote = new Array<emotePackage>();
    this._dynamicEmote = new Array<emotePackage>();
  }

  public get replyEmote() {
    return this._replyEmote;
  }

  public get dynamicEmote() {
    return this._dynamicEmote;
  }

  loadCache() {
    try {
      let count = 0;
      let res = this.result;
      if (res != emoteResult.success && res != emoteResult.dynamic) {
        this.loadEmote('dynamic').then((res) => {
          if (res.success) {
            this.result = emoteResult.dynamic;
            this._dynamicEmote.length = 0;
            for (var data of res.data) {
              if (utils.isEmpty(data.emote) || data.emote?.length == 0)
                continue;
              this._dynamicEmote.push(data);
            }
            count++;
          }
          if (this._dynamicEmote.length > 0 && count == 2)
            this.result = emoteResult.success;
        });
      }
      if (res != emoteResult.success && res != emoteResult.reply) {
        this.loadEmote('reply').then((res) => {
          if (res.success) {
            this.result = emoteResult.reply;
            this._replyEmote.length = 0;
            for (var data of res.data) {
              if (utils.isEmpty(data.emote) || data.emote.length == 0)
                continue;
              this._replyEmote.push(data);
            }
            count++;
          }
          if (this._replyEmote.length > 0 && count == 2)
            this.result = emoteResult.success;
        });
      }
    } catch (e) {
      logger.error(e);
    }
  }

  private loadEmote(type: string): Promise<returnModel<Array<emotePackage>>> {
    var self = this;
    return new Promise((resolve) => {
      try {
        let info = new apiInfo("https://api.bilibili.com/x/emote/user/panel", `&business=${type}`, true);
        this.client.getResult(info).then((res) => {
          if (res.code == 0) {
            var data = res.data.packages as Array<emotePackage>;
            resolve(self.buildSuccessResult<Array<emotePackage>>(data));
          } else {
            var failed = self.buildFailedResult<Array<emotePackage>>(res.message);
            resolve(failed);
          }
        });
      } catch (e) {
        logger.error(e);
        resolve(this.buildExceptionResult<Array<emotePackage>>(e));
      }
    });
  }
}
export default new emoteClient();